from typing import Any
from fastapi import Query
from sqlalchemy import func
from sqlalchemy.orm import Session, joinedload
from app.database import engine


def pagination(page: int, page_size: int, model, filter_condition: Any = None, joined: Any = None):
    with Session(engine) as session:
        offset = (page - 1) * page_size
        count = session.query(func.count()).select_from(model).scalar()
        query: Query = session.query(model)
        if filter_condition:
            query = query.filter(filter_condition)
        if joined:
            query = query.options(joinedload(joined))
        data = query.offset(offset).limit(page_size).all()
    return {'list': data, 'total': count}
